package com.sxsihe.heartmate.util;

import android.content.Context;
import android.os.AsyncTask;
import com.daimajia.numberprogressbar.NumberProgressBar;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import java.io.File;

import cn.pedant.SweetAlert.widget.SweetAlertDialog;
import org.json.JSONException;
import org.json.JSONObject;

public class HttpMultipartPost extends AsyncTask<String, Integer, String> {
    static String SERVER_ERROR = "SERVER_ERROR";
    private Context context;
    private String filePath;
    private NumberProgressBar pd;
    private long totalSize;
    SharePreferenceUtil spu;


    public HttpMultipartPost(Context context, String filePath, NumberProgressBar np) {
        this.context = context;
        this.filePath = filePath;
        this.pd = np;
        if (spu == null) {
            spu = SharePreferenceUtil.getInstance(context);
        }
    }

    @Override
    protected String doInBackground(String... params) {
        String serverResponse = null;
        HttpClient httpClient = new DefaultHttpClient();
        HttpContext httpContext = new BasicHttpContext();
        FileBody fileBody = new FileBody(new File(filePath));
        String url = "http://"+spu.get("server_ip","");
        if(spu.get("server_port","").equals("")){
            url +=":"+spu.get("server_port","");
        }
        url +="/zhcjhy/ecgfileShowAction.do?action=uploadfile";
        String loginName = "";
        PersistentCookieStore cookieStore = new PersistentCookieStore(context);
        for (Cookie cookie : cookieStore.getCookies()) {
            if (cookie.getName().equals("loginname") && cookie.getDomain().equals(spu.get("server_ip", ""))) {
                loginName = cookie.getValue();
            }
        }
        String start = fileBody.getFilename().replace(".data","");
        String end = String.valueOf(fileBody.getFile().lastModified());
        String filename = loginName+"_"+start+"_"+end+".data";

        HttpPost httpPost = new HttpPost(url);
        try {
            CustomMultipartEntity multipartContent = new CustomMultipartEntity(
                    new CustomMultipartEntity.ProgressListener() {
                        @Override
                        public void transferred(long num) {
                            publishProgress((int) ((num / (float) totalSize) * 100));
                        }
                    });
            multipartContent.addPart(filename, fileBody);
            totalSize = multipartContent.getContentLength();
            httpPost.setEntity(multipartContent);
            HttpResponse response = httpClient.execute(httpPost, httpContext);
            serverResponse = EntityUtils.toString(response.getEntity());
        } catch (Exception e) {
            e.printStackTrace();
            serverResponse = SERVER_ERROR;
        }finally {
            httpClient.getConnectionManager().shutdown();
        }
        return serverResponse;
    }

    public void onPostExecute(String serverResponse){
        try {
            JSONObject json = new JSONObject(serverResponse);
            if(!json.getBoolean("success")){
                new SweetAlertDialog(context, SweetAlertDialog.ERROR_TYPE)
                        .setTitleText("出错了")
                        .setContentText(json.getString("msg"))
                        .show();
            }
        } catch (JSONException e) {
            new SweetAlertDialog(context, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("出错了")
                    .setContentText("上传文件异常")
                    .show();
            e.printStackTrace();
        }
    }

    @Override
    protected void onProgressUpdate(Integer... progress) {
        pd.setProgress(progress[0]);
    }



    @Override
    protected void onCancelled() {
    }

}
